let CtpI18nFun = null;
/**
 * 优先使用外层的i18n实现
 */
if ((window._ctpTop || window.top).$ && (window._ctpTop || window.top).$.i18n) {
	CtpI18nFun = (window._ctpTop || window.top).$.i18n;
} else if ((window._ctpTop || window.top).$ && (window._ctpTop || window.top).$i18n) {
	CtpI18nFun = (window._ctpTop || window.top).$i18n;
} else {
	const getI18n = (win) => {
		if (!win) {
			return null;
		}
		if (win.$ && win.$.i18n) {
			return win.$.i18n;
		} else if (win.$ && win.$i18n) {
			return win.$i18n;
		} else {
			if (win !== win.parent) {
				return getI18n(win.parent);
			} else {
				return null;
			}
		}
	};
	CtpI18nFun = getI18n(window);
}
/**
 * 外层没有实现，本页面实现
 */
if (CtpI18nFun === null) {
	const baseUrl = `${_ctxPath}/i18n_${_locale}.js`;
	let staticSuffix = _staticSuffix;
	if (typeof (staticSuffix) === 'string') {
		staticSuffix = '?timestamp=' + new Date().getTime();
	}
	const i18nUrl = `${baseUrl}${staticSuffix}`;
	let i18nDateLoadTimes = 0;
	const initAjax = () => {
		const xhrs = [
			function () {
				return new XMLHttpRequest();
			},
			function () {
				return new ActiveXObject('Msxml2.XMLHTTP');
			},
			function () {
				return new ActiveXObject('Msxml3.XMLHTTP');
			},
			function () {
				return new ActiveXObject('Microsoft.XMLHTTP');
			}
		];
		for (let i = 0; i < xhrs.length; i++) {
			try {
				return xhrs[i]();
			} catch (e) {
				continue;
			}
		}
		return {};
	};
	const loadI18nData = () => {
		let ajax = initAjax();
		ajax.open('get', i18nUrl, false);
		ajax.send(null);
		// eslint-disable-next-line no-eval
		eval(ajax.responseText);
	};
	CtpI18nFun = (...args) => {
		let key = args[0];
		try {
			let msg = '';
			if (!CTPLang || !CTPLang[_locale]) {
				if (i18nDateLoadTimes > 5) {
					// 现在国际化无休止的加载！
					return key;
				}
				i18nDateLoadTimes++;
				loadI18nData();
			}
			let lang = CTPLang[_locale];
			if (!lang) {
				return key;
			}
			msg = lang[key + _editionI18nSuffix.toUpperCase()];
			if (!msg) {
				msg = lang[key + _editionI18nSuffix.toLowerCase()];
			}
			if (!msg) {
				msg = lang[key];
			}
			if (msg && args.length > 1) {
				for (let i = 0; i < args.length - 1; i++) {
					let regEx = new RegExp('\\{' + i + '\\}', 'g');
					let repMe = '' + args[i + 1];
					if (repMe.indexOf('$_') !== -1) {
						repMe = repMe.replace('$_', '$$_');
					}
					msg = msg.replace(regEx, repMe);
				}
			}

			if (typeof msg === 'undefined' || msg === '') {
				msg = key;
			}
			return msg;
		} catch (e) {
			console.warn('format error', e, args);
		}
		return '';
	};
}

const CtpI18n = {
	install(Vue) {
		window.$i18n = CtpI18nFun;
		Vue.prototype.$i18n = CtpI18nFun;
	}
};
export default CtpI18n;
